***CAP GAINS***

foreach n in 96 98 00 {
tempfile capgain_h`n'
use "${original}H`n'N_H.dta", clear
if `n' == 96 | `n' == 98 g year=19`n'
if `n' == 00 g year = 2000
rename *,lower
ren ?pn_cs pn
save `capgain_h`n''
*
use "${original}H`n'N_R.dta", clear
if `n' == 96 | `n' == 98 g year=19`n'
if `n' == 00 g year = 2000
rename *,lower
merge 1:1 hhid pn using `capgain_h`n'', nogen
save capgain_`n'.dta, replace
}

foreach n in 02 04 06 08 10 12 14 {
use "${original}H`n'R_H.dta", clear
g year = 20`n'
rename *,lower
save capgain_`n'.dta, replace
}

*1996
use capgain_96.dta, clear
keep e4894 e4905 year hhid pn esubhh
ren e4894 stck_buy
ren e4905 stck_sell_only
save capgain_96.dta,replace

*1998
use capgain_98.dta, clear
keep f5630 f5641 year hhid pn fsubhh
ren f5630 stck_buy
ren f5641 stck_sell_only
save capgain_98.dta, replace

*2000
use capgain_00.dta, clear
keep g5983 g5994 year hhid pn gsubhh
ren g5983 stck_buy
ren g5994 stck_sell_only
save capgain_00.dta, replace

*2002-2014
foreach n in 02 04 06 08 10 12 14 {
use capgain_`n'.dta, clear
if `n' == 02 drop gsubhh
if `n' == 04 drop hsubhh
if `n' == 06 drop jsubhh
if `n' == 08 drop ksubhh
if `n' == 10 drop lsubhh
if `n' == 12 drop msubhh
if `n' == 14 drop nsubhh
ren ?subhh subhh
ren ?r# .r#
ren ?pn_cs pn
keep r061 r072 year hhid pn subhh
ren r061 stck_buy
ren r072 stck_sell_only
save capgain_`n'.dta, replace
}

*Append
use capgain_96.dta, clear
append using capgain_98.dta capgain_00.dta capgain_02.dta capgain_04.dta capgain_06.dta capgain_08.dta capgain_10.dta capgain_12.dta capgain_14.dta
save capgain.dta, replace


use capgain.dta, clear

*fin_activity

destring *,replace
g hhidpn = 1000 * hhid + pn
save capgain_pan,replace


use sample_cams,clear
destring subhh,replace
merge 1:1 hhid pn year using capgain_pan, keep(1 3) gen(_capgain)
save sample_capgain,replace

*Erase temporary datasets
foreach n in 96 98 00 02 04 06 08 10 12 14 {
erase capgain_`n'.dta
}
erase capgain.dta
erase sample_cams.dta
erase capgain_pan.dta
